package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.modules.ims.dto.TaxItemDto;
import com.yonyou.sto.modules.ims.model.ImsBuyer;
import com.yonyou.sto.modules.ims.mapper.ImsBuyerMapper;
import com.yonyou.sto.modules.ims.model.ImsParty;
import com.yonyou.sto.modules.ims.model.ImsTaxItem;
import com.yonyou.sto.modules.ims.service.ImsBuyerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aegon
 * @since 2020-09-28
 */
@Service
public class ImsBuyerServiceImpl extends ServiceImpl<ImsBuyerMapper, ImsBuyer> implements ImsBuyerService {

    @Override
    public CommonResult create(ImsBuyer buyer) {
//        ImsBuyer sn = getBuyerByBuyerTaxSn(buyer.getBuyerTaxSn());
//        if (!BeanUtil.isEmpty(sn)) return CommonResult.failed("已有重复税号");
        buyer.setCreateTime(new Date());
        buyer.setStatus(1);
        buyer.setSort(0);
        return CommonResult.success(save(buyer));
    }

    @Override
    public CommonResult info(Long id) {
        ImsBuyer byId = getById(id);
        return CommonResult.success(byId);
    }

    @Override
    public CommonResult findByBuyerName(String buyerName) {
        List<ImsBuyer> list = baseMapper.getBuyerByBuyerName(buyerName);
        return list.size()==0?CommonResult.failed():CommonResult.success(list);
    }

    @Override
    public CommonResult delete(Long id) {
        ImsBuyer buyer = new ImsBuyer();
        buyer.setId(id);
        buyer.setStatus(0);
        boolean result = updateById(buyer);
        if (result) return CommonResult.success("删除成功");
        return CommonResult.failed("删除失败");
    }

    @Override
    public Page<ImsBuyer> buyerList(String keyword, Integer pageSize, Integer pageNum) {
        Page<ImsBuyer> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ImsBuyer> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsBuyer> lambda = wrapper.lambda();
        lambda.eq(ImsBuyer::getStatus, 1);
        if (StrUtil.isNotEmpty(keyword)) {
            lambda.like(ImsBuyer::getBuyerName, keyword);
        }
        return page(page, wrapper);
    }

    @Override
    public ImsBuyer getBuyerByBuyerTaxSn(String buyerTaxSn) {
        return baseMapper.getBuyerByBuyerTaxSn(buyerTaxSn);
    }

    @Override
    public CommonResult importBuyer(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return CommonResult.failed("请上传excel2007版本及以上的xlsx文件");
        }

        try {
            XSSFWorkbook xssf = new XSSFWorkbook(file.getInputStream());
            int numberOfSheets = xssf.getNumberOfSheets();

            List<ImsBuyer> buyers = new ArrayList<>();
            for (int i = 0; i < numberOfSheets; i++) {// 表
                XSSFSheet sheet = xssf.getSheetAt(i);
                int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
                for (int j = 0; j < physicalNumberOfRows; j++) {// 行
                    if (j == 0) continue;
                    XSSFRow row = sheet.getRow(j);
                    int physicalNumberOfCells = row.getPhysicalNumberOfCells();

                    ImsBuyer buyer = new ImsBuyer();
                    Field[] f = buyer.getClass().getDeclaredFields();

                    for (int k = 0; k < physicalNumberOfCells; k++) {// 单元格
                        row.getCell(k).setCellType(Cell.CELL_TYPE_STRING);
                        XSSFCell cell = row.getCell(k);
                        String stringCellValue = cell.getStringCellValue();
                        // 此方法要求导入格式必须正确 索引从1开始
                        String attributeName = f[k + 3].getName();
                        String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
                        Method setMethod = buyer.getClass().getMethod("set" + methodName, String.class);
                        setMethod.invoke(buyer, stringCellValue);

                        buyer.setCreateTime(new Date());
                        buyer.setStatus(1);
                    }
                    buyers.add(buyer);
                }
            }
            boolean b = saveBatch(buyers);
            return CommonResult.success("上传文件成功");
        } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return CommonResult.failed("上传文件格式不正确");
        }
    }
}
